<?php
/**
 * This file is part of the Jindai.
 * @copyright Copyright (c) 2019 All Rights Reserved.
 * @author jindai <jindai0305@gmail.com>
 */

namespace App\Support;

/**
 * Class Github
 * @package App\Support
 *
 * @property-read Request $client
 * @property-read string $client_id
 * @property-read string $client_secret
 */
class Github
{
    public $client;

    private $client_id;
    private $client_secret;

    public function __construct(Request $client)
    {
        $this->client = $client;
        $this->client_id = config('website.oauth.github.client_id');
        $this->client_secret = config('website.oauth.github.client_secret');
    }

    /**
     * 转向授权
     */
    public function turnToAuthorization()
    {
        return redirect()->away('https://github.com/login/oauth/authorize?client_id=' . $this->client_id . '&scope=user:email');
    }

    /**
     * @param $code
     * @return mixed|\Psr\Http\Message\ResponseInterface|string
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function getAccessToken($code)
    {
        return $this->client->guzzleHttpRequest('GET', 'https://github.com/login/oauth/access_token?' . http_build_query([
                'code' => $code,
                'client_id' => $this->client_id,
                'client_secret' => $this->client_secret,
            ]));
    }

    /**
     * @param $code
     * @return mixed|\Psr\Http\Message\ResponseInterface|string
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function getUserInfo($code)
    {
        $token = $this->getAccessToken($code);

        $user = $this->client->guzzleHttpRequest('GET', 'https://api.github.com/user?' . $token->getBody()->getContents());

        return $user;
    }
}
